package com.laker.autotest.api.core;

import com.laker.autotest.api.core.auth.AuthTokenProvider;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * 认证拦截器，支持 Bearer、Basic 等多种 token 类型
 */
public class AuthAndBaseUriInterceptor implements Interceptor {

    private final AuthTokenProvider tokenProvider;

    public AuthAndBaseUriInterceptor(AuthTokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        String authHeader = tokenProvider.getAuthHeader();
        Request.Builder builder = originalRequest.newBuilder();
        if (authHeader != null && !authHeader.isEmpty()) {
            builder.header("Authorization", authHeader);
        }
        builder.header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .method(originalRequest.method(), originalRequest.body())
                .url(originalRequest.url());
        return chain.proceed(builder.build());
    }
}